<html data-framework="vue">

<head>
  <meta charset="utf-8" />
  <title>Todo</title>

  <!-- <script src="https://unpkg.com/director@1.2.8/build/director.js"></script> -->
  <style>
    [v-cloak] {
      display: none;
    }
  </style>
  <link rel="stylesheet" href="./css/style.css" />
</head>

<body>
  <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
  <script src="./js/main.js"></script>
  <section id="app" class="todoapp">
    <todo-header @add="onAdd"></todo-header>
    <section class="main">
      <input type="checkbox" class="toggle-all" />
      <ul class="todo-list">
        <todo-item v-for="(item,index) in filterDone"  v-model:done="item.done"
          @delete="onDelete(item.id)"
          v-model:title="item.title"
          v-model:edit="item.edit"
          @dblclick="item.edit=true"
          ></todo-item>
      </ul>
    </section>
    <todo-footer :undo="undoCount" v-model:filter="filter"></todo-footer>
  </section>
  <footer class="info">
    <p>双击待办项以编辑。</p>
  </footer>
  <script>
    const app = Vue.createApp({
      data() {
        return {
          filter: '',
          todoList: [
            { id: 1, title: '吃饭', done: false, edit:false},
            { id: 2, title: '睡觉', done: true, edit:false },
          ]
        }
      },
      components: {
        TodoHeader, TodoItem, TodoFooter
      },
      //创建阶段 为每个对象添加edit:false 属性
      /* created(){
          this.todoList.foreach((item)=>item.edit=false)
      }, */
      methods: {
        // 添加待办事项，e:事件对象（子组件传过来的值）
        //unshift：将对象添加到数组第一个元素，id使用时间作为主键，（删除依据）
        onAdd(e) {
          if (e === '') return;
          this.todoList.unshift({
            id: Date.now(),
            title: e,
            done: false,
            edit:false
          });
        

        },
        //删除：根据id删除，先查询对应下标，再使用splice删除
        onDelete(id) {
          let index = this.todoList.findIndex((item) => item.id === id);
          if (index != -1) {
            this.todoList.splice(index, 1)
          }
        }
      },
      computed: {
        // 获取未完成的待办事项的长度
        undoCount() {
          //console.log(this.todoList.filter((item)=>item.done===false).length);
          return this.todoList.filter((item) => item.done === false).length
        },
        // 获取对应筛选条件的数组，然后将其渲染到列表中
        filterDone() {
          console.log(this.filter);
          if (this.filter === '') return this.todoList;
          return this.todoList.filter((item) => (item.done === this.filter))
        }
      }

    });
    app.mount('#app')
  </script>
</body>

</html>